{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# `mlc-llm` 简介"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import set_env"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "MLC LLM 是机器学习编译器和高性能部署引擎，专为大型语言模型设计。该项目的使命是让每个人都能在自己的平台上原生地开发、优化和部署 AI 模型。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "下载模型：\n",
    "```bash\n",
    "# git clone https://huggingface.co/mlc-ai/Llama-3-8B-Instruct-q4f16_1-MLC\n",
    "git clone https://hf-mirror.com/mlc-ai/Hermes-3-Llama-3.1-8B-q4f32_1-MLC {temp_dir}/mlc-ai/Hermes-3-Llama-3.1-8B-q4f32_1-MLC\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "下面是 hello world 的示例："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "hide-ouput"
    ]
   },
   "outputs": [],
   "source": [
    "from mlc_llm import MLCEngine\n",
    "\n",
    "# Create engine\n",
    "# model = \"HF://mlc-ai/Llama-3-8B-Instruct-q4f16_1-MLC\" # 原始模型地址\n",
    "model = f\"{temp_dir}/mlc-ai/Hermes-3-Llama-3.1-8B-q4f32_1-MLC\"\n",
    "engine = MLCEngine(model)\n",
    "\n",
    "# Run chat completion in OpenAI API.\n",
    "for response in engine.chat.completions.create(\n",
    "    messages=[{\"role\": \"user\", \"content\": \"What is the meaning of life?\"}],\n",
    "    model=model,\n",
    "    stream=True,\n",
    "):\n",
    "    for choice in response.choices:\n",
    "        print(choice.delta.content, end=\"\", flush=True)\n",
    "print(\"\\n\")\n",
    "\n",
    "engine.terminate()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "也支持异步操作："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "hide-output"
    ]
   },
   "outputs": [],
   "source": [
    "import asyncio\n",
    "from typing import Dict\n",
    "\n",
    "from mlc_llm.serve import AsyncMLCEngine\n",
    "\n",
    "# model = \"HF://mlc-ai/Llama-3-8B-Instruct-q4f16_1-MLC\"\n",
    "model = f\"{temp_dir}/mlc-ai/Hermes-3-Llama-3.1-8B-q4f32_1-MLC\"\n",
    "prompts = [\n",
    "    \"Write a three-day travel plan to Pittsburgh.\",\n",
    "    \"What is the meaning of life?\",\n",
    "]\n",
    "\n",
    "\n",
    "async def test_completion():\n",
    "    # Create engine\n",
    "    async_engine = AsyncMLCEngine(model=model)\n",
    "\n",
    "    num_requests = len(prompts)\n",
    "    output_texts: Dict[str, str] = {}\n",
    "\n",
    "    async def generate_task(prompt: str):\n",
    "        async for response in await async_engine.chat.completions.create(\n",
    "            messages=[{\"role\": \"user\", \"content\": prompt}],\n",
    "            model=model,\n",
    "            stream=True,\n",
    "        ):\n",
    "            if response.id not in output_texts:\n",
    "                output_texts[response.id] = \"\"\n",
    "            output_texts[response.id] += response.choices[0].delta.content\n",
    "\n",
    "    tasks = [asyncio.create_task(generate_task(prompts[i])) for i in range(num_requests)]\n",
    "    await asyncio.gather(*tasks)\n",
    "\n",
    "    # Print output.\n",
    "    for request_id, output in output_texts.items():\n",
    "        print(f\"Output of request {request_id}:\\n{output}\\n\")\n",
    "\n",
    "    async_engine.terminate()\n",
    "\n",
    "\n",
    "# asyncio.run(test_completion())\n",
    "await test_completion()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "py313",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
